package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.ResourceDto;
import com.zzyl.entity.Dept;
import com.zzyl.entity.Resource;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.mapper.RoleResourceMapper;
import com.zzyl.service.ResourceService;
import com.zzyl.utils.NoProcessing;
import com.zzyl.utils.ThreadLocalUtil;
import com.zzyl.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class ResourceServiceImpl implements ResourceService {

    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private RoleResourceMapper roleResourceMapper;
    /**
     * 根据用户id查询对应的资源数据
     *
     * @return
     */
    @Override
    public List<ResourceVo> findResourceList(ResourceDto dto) {
        List<Resource> list = resourceMapper.selectList(dto);
        //将集合中的Resource转成ResourceVo
        return BeanUtil.copyToList(list, ResourceVo.class);
    }

    @Override
    public TreeVo resourceTree(ResourceDto dto) {
        //1. 查询所有资源列表（状态为0启用）
        dto.setDataState(SuperConstant.DATA_STATE_0);
        dto.setResourceType(SuperConstant.MENU);
        List<Resource> resourceList = resourceMapper.selectList(dto);

        if (CollUtil.isEmpty(resourceList)) {
            throw new RuntimeException("资源信息未定义");
        }

        //2. 提取根节点（智慧养老院 节点）
        Resource rootResource = CollUtil.findOneByField(resourceList, "resourceNo", SuperConstant.ROOT_RESOURCE_PARENT_ID);

        //3. 通过递归方法，将 resourceList 列表 全部加载到 rootResource 根节点上去
        TreeItemVo treeItemVo = recursionResourceTree(rootResource, resourceList);

        //4. 将 treeItemVo 树  封装到集合中，放到TreeVo中返回
        return TreeVo.builder()
                .items(List.of(treeItemVo))
                .build();
    }

    @Override
    public void addResource(ResourceDto dto) {
        //1. 将 dto 的数据拷贝到Resource对象
        Resource resource = BeanUtil.toBean(dto, Resource.class);

        //2. 处理资源编号
        Resource parentResource = resourceMapper.selectByResourceNo(dto.getParentResourceNo());
        String resourceNo = createResourceNo(resource, parentResource);

        //3. 设置资源编号
        resource.setResourceNo(resourceNo);

        //4. 添加到数据库
        resourceMapper.insert(resource);
    }

    @Override
    public void updateResource(ResourceDto resourceDto) {
        resourceDto.setParentResourceNo(null); //禁止修改父节点
        //转换
        Resource resource = BeanUtil.toBean(resourceDto, Resource.class);
        resourceMapper.updateByPrimaryKeySelective(resource);
    }

    /**
     * 启用禁用
     *
     * @param resourceVo
     * @return
     */
    @Override
    public void isEnable(ResourceVo resourceVo) {
        //启用菜单
        if (StrUtil.equals(resourceVo.getDataState(), SuperConstant.DATA_STATE_0)) {
            //判断父级菜单是否是禁用，如果是禁用，不允许启用
            String parentResourceNo = resourceVo.getParentResourceNo();
            Resource parentResource = resourceMapper.selectByResourceNo(parentResourceNo);
            if (parentResource != null && parentResource.getDataState().equals("1")) {
                throw new BaseException(BasicEnum.PARENT_MENU_DISABLE);
            }
        }

        //判断是否有子菜单，如果有子菜单，则一起启用或禁用
        String resourceNo = resourceVo.getResourceNo();
        resourceMapper.updateByResourceNo(resourceNo, resourceVo.getDataState());
        resourceMapper.updateByParentResourceNo(NoProcessing.processString(resourceNo), resourceVo.getDataState());
    }

    /**
     * 删除菜单
     *
     * @param resourceNo
     */
    @Override
    public void deleteByResourceNo(String resourceNo) {
        //判断是否有子菜单，则不能删除
        int result = resourceMapper.hasChildByMenuId(resourceNo);
        if (result > 0) throw new RuntimeException("存在子菜单,不允许删除");

        //如果当前菜单被角色引用，则不能删除
        result = roleResourceMapper.checkMenuExistRole(resourceNo);
        if (result > 0) throw new RuntimeException("菜单已分配,不允许删除");

        //菜单启用状态,不能删除
        Resource resource = resourceMapper.selectByResourceNo(resourceNo);
        if (resource == null || resource.getDataState().equals(SuperConstant.DATA_STATE_0)) {
            throw new RuntimeException("菜单启用状态,不能删除");
        }

        resourceMapper.deleteByResourceNo(resourceNo);
    }



    private String createResourceNo(Resource resource, Resource parentResource) {
        //判断是否是按钮，如果是按钮，则不限制层级
        if (!StrUtil.equals(resource.getResourceType(), SuperConstant.BUTTON)) {
            if (NoProcessing.processString(parentResource.getResourceNo()).length() / 3 >= 5) {
                //判断资源编号是否大于三级
                //100 001 000 000 000
                //100 001 001 000 000
                //100 001 001 001 000
                //100 001 001 001 001 001
                throw new BaseException(BasicEnum.RESOURCE_DEPTH_UPPER_LIMIT);
            }

        }

        //根据父资源编号查询子资源
        ResourceDto dto = ResourceDto.builder().parentResourceNo(parentResource.getResourceNo()).build();
        List<Resource> resources = resourceMapper.selectList(dto);
        if (ObjectUtil.isEmpty(resources)) {
            //无下属节点，创建新的节点编号  100 001 001 001 000--->100 001 001 001 001
            return NoProcessing.createNo(parentResource.getResourceNo(), false);
        } else {
            //有下属节点，在已有的节点上追加，先获取已有节点的最大值--100001003000000
            Long maxNo = resources.stream().map(r -> Long.valueOf(r.getResourceNo())).max(Comparator.comparing(i -> i)).get();
            return NoProcessing.createNo(String.valueOf(maxNo), true);
        }
    }

    private TreeItemVo recursionResourceTree(Resource rootResource, List<Resource> resourceList) {
        //1. 构建一个 TreeItemVo 树对象
        TreeItemVo treeItemVo = TreeItemVo.builder()
                .id(rootResource.getResourceNo()) //资源编号
                .label(rootResource.getResourceName()) //资源名称
                .build();

        //2. 从资源列表中提取根节点的子节点     //判断resource是否是rootResource的子节点
        Collection<Resource> childrenResource = CollUtil.filterNew(resourceList,
                resource -> StrUtil.equals(resource.getParentResourceNo(), rootResource.getResourceNo()));
        if (CollUtil.isEmpty(childrenResource)) {
            return treeItemVo;
        }

        //3. 处理子节点列表，map映射，将 Resource 映射成  TreeItemVo
        List<TreeItemVo> children = childrenResource.stream().map(resource -> recursionResourceTree(resource, resourceList)).collect(Collectors.toList());

        //4. 给 treeItemVo 设置子节点，返回
        treeItemVo.setChildren(children);

        return treeItemVo;
    }



    @Override
    public List<MenuVo> getMyMenus() {
        Long userId = 1671403256519078138L;
        //查询数据
        List<MenuVo> menuVoList = resourceMapper.selectMenuByUserId(userId);
        //构建 parentNo -> List<MenuVo> 的映射
        Map<String, List<MenuVo>> parentMap = menuVoList.stream().collect(Collectors.groupingBy(MenuVo::getParentResourceNo));

        //递归构建我的菜单信息
        buildTree(menuVoList, parentMap);
        return parentMap.get(SuperConstant.ROOT_RESOURCE_PARENT_ID);
    }


    /**
     * 递归构建我的菜单信息（已提供）
     */
    private void buildTree(List<MenuVo> menuVoList, Map<String, List<MenuVo>> parentMap) {
        menuVoList.forEach(menuVo -> {
            //补全数据
            menuVo.setMeta(MenuMetaVo.builder().title(menuVo.getName()).build());
            menuVo.setRedirect("/" + menuVo.getName());
            //根据当前资源编号查询子资源
            List<MenuVo> childrenList = parentMap.get(menuVo.getResourceNo());
            if (CollUtil.isNotEmpty(childrenList)) {
                buildTree(childrenList, parentMap);
                menuVo.setChildren(childrenList);
            }
        });
    }
}
